package com.yuyang.wifi.utils.network;


import android.os.Bundle;
import android.util.Log;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.utils.NetworkUtils;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.eventbus.BaseEventManager;

import java.io.IOException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by ttr01 on 2016/4/8.
 */
public abstract class BaseDataSubscriber<T extends BaseResult> extends Subscriber<T> {
    HttpErrorHandler httpErrorHandler;
    ProgressHandler progressHandler;

    public BaseDataSubscriber(HttpErrorHandler httpErrorHandler) {
        this.httpErrorHandler = httpErrorHandler;
    }

    public BaseDataSubscriber(HttpErrorHandler httpErrorHandler, ProgressHandler progressHandler) {
        this.httpErrorHandler = httpErrorHandler;
        this.progressHandler = progressHandler;
    }


    @Override
    public void onCompleted() {
        if (progressHandler != null) {
            progressHandler.loadingComplete();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (progressHandler != null) {
            progressHandler.loadingStart();
        }
    }

    @Override
    public void onNext(T t) {
        if (t != null && (t.isSuccess() || t.isDataEmpty())) {
            onDataNext(t);
        } else {

            int resultCode = t.getResultCode();
            Log.e("resultCode", "resultCode==" + resultCode);

            if (resultCode == 3) {
                Bundle bundle = new Bundle();
                ToastUtils.showShortToast(MyApplication.getInstance(),t.getErrorMessage());
                BaseEventManager.post(bundle, "token_lose_efficacy");//发送eventbus消息通知token失效
            } else if (resultCode == 401) {


            } else {
                httpErrorHandler.onHttpError(t);
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if (progressHandler != null) {
            progressHandler.loadingComplete();
        }
        e.printStackTrace();
        if (!NetworkUtils.isConnected(MyApplication.getInstance())) {
            ToastUtils.showShortToast(MyApplication.getInstance(), "当前无可用的网络连接\n请打开手机网络开关");
            return;
        }
        if (e instanceof HttpException) {
            HttpException e1 = (HttpException) e;
            //ToastUtils.showShortToast(MyApplication.getInstance(), "请检查网络连接并重试哦~");
        } else if (e instanceof IOException) {
            //ToastUtils.showShortToast(MyApplication.getInstance(), "请检查网络连接并重试~");
        }
//
//        else {
//            ToastUtils.showShortToast(MyApplication.getInstance(), "出小差了，请稍等哦~" + e.getMessage());
//        }
        httpErrorHandler.onHttpException(e);
        Log.d("network","network"+e.getMessage());

    }

    public abstract void onDataNext(T t);

}
